package client.gui;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimerTask;
import java.util.Timer;


import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;

import client.GetFileFromServer;
import client.SendFileToServer;

import messages.*;
import messages.MessageExtraTimeCheckReply.ErrMsg;

import sharedspace.*;

import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
/**
 * this class let student to download manual test and to upload it back to server
 * @author Amir S.
 * @author Jacob C.
 * @author Maya G.
 * @author Michael V.
 *
 */
public class GUI_ManualTest extends JPanel {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ExecuteTest executeTest;
	private Student student;
	private Client_GUI ms;
	private JButton downloadTest;
	private JButton uploadTest;
	private JLabel titleLabel;
	private JLabel lblTestDuration;
	private JLabel lblClock;
	private File file;
	private StudentInTest studentInTest;
	private GUI_ImagePanel background;
	
	public GUI_ManualTest(Client_GUI ms, ExecuteTest executeTest, Student student)
	{
		this.executeTest = executeTest;
		this.student = student;
		this.ms = ms;
		
		intitialize();
	}
	/**
	 * Initialize screen
	 */
	public void intitialize()
	{
		this.setSize(1000, 700);
		this.setLayout(null);
	
		
		background = new GUI_ImagePanel(new ImageIcon("images/background1.jpg").getImage());
		background.setSize(new Dimension(1000, 700));
		
		
		this.add(getDownloadTest());
		this.add(getUploadTest());
		this.add(getTitleLabel());
		add(background);
		
		lblTestDuration = new JLabel("Test Duration: "+executeTest.getTest().getTestDuration()+" minutes");
		lblTestDuration.setFont(new Font("Tahoma", Font.PLAIN, 16));
		lblTestDuration.setBounds(133, 151, 237, 30);
		background.add(lblTestDuration);
		
		lblClock = new JLabel();
		lblClock.setFont(new Font("Tahoma", Font.PLAIN, 16));
		lblClock.setBounds(133, 181, 237, 30);
		
		setStuedntInTest();
	    startTimer();
	    automaticCloser();
		
		//this.add(chooser);
		
		
	
	}
	
	/**
	 * button to download test
	 * @return
	 */
	public JButton getDownloadTest()
	{
		downloadTest = new JButton("download");
		downloadTest.setBounds(135, 275, 102, 30);
		downloadTest.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
			try
			{
				MessageGetWordFile msggwf = new MessageGetWordFile(executeTest);
				ms.client.sendToServer(msggwf);
				MyFile myFile = (MyFile)ms.client.GetMessage();
				File file = FileHandler.saveFileDialog("Save Test");
			   	String path = file.getAbsolutePath();
			    GetFileFromServer gffs = new GetFileFromServer(path);
				gffs.getFileFromServer(myFile);
				uploadTest.setEnabled(true);
			    			
			} 
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
			}
		});
		return downloadTest;
	}
	/**
	 * button to upload test
	 * @return
	 */
	public JButton getUploadTest()
	{
		uploadTest = new JButton("upload");
		uploadTest.setBounds(135, 234, 102, 30);
		uploadTest.setEnabled(false);
		uploadTest.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				try
				{
					File file = FileHandler.openFileDialog("Upload");
					
						String path = file.getAbsolutePath();
						System.out.println(path);
						SendFileToServer sfts = new SendFileToServer(path);
						MyFile myFile = sfts.sendFileToServer(executeTest, student);
						MessageSendWordTest msgswt = new MessageSendWordTest(myFile, student, executeTest); 
						ms.client.sendToServer(msgswt);  				
						ms.setContentPane(ms.stdnt);
				
					
				
					
				} 
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
		return uploadTest;
	}
	
	public JLabel getTitleLabel()
	{
		titleLabel = new JLabel("Manual Test");
		titleLabel.setForeground(Color.BLUE);
		titleLabel.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 38));
		titleLabel.setBounds(424, 58, 245, 67);
		return titleLabel;
	}
	
	/**
	 * update StudentInTest and send it to database;
	 */
	public void setStuedntInTest()
	{
		studentInTest = new StudentInTest();
		Timestamp time;
		
		/*------------------------------Taking-Time-stamp-------------------------------------------------*/
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String startTime = DateUtils.now("yyyy-MM-dd HH:mm:ss");
		java.util.Date parseDate;
		
		try {
			parseDate = dateFormat.parse(startTime);
			time = new Timestamp(parseDate.getTime());
			studentInTest.setStartTest(time);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(startTime);
		
		/*------------------------Creating-StudentInTest-------------------------------------------------*/
		studentInTest.setExecuteTestID(ms.stdnt.getExecuteTest().getExecuteTestID());
		studentInTest.setStudent(ms.stdnt.getStudent());
		studentInTest.setStudentComputerGrade(-1);
		long t = studentInTest.getStartTest().getTime();
		long m = 60000;
		studentInTest.setEndTest(new Timestamp(t-m));
		studentInTest.setTestCheckedComplete(false);
		studentInTest.setWordTestCheckedPath(null);
		
		/*-----------------------Sending-StudentInTest--------------------------------------------------*/
		MessageStudentInTest msgsit = new MessageStudentInTest(studentInTest,ms.stdnt.getExecuteTest());
		try
		{
			ms.client.sendToServer(msgsit);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		
	}
	
	public void startTimer()
	{
		
		MessageStartTime MsgSt = new MessageStartTime(executeTest.getExecuteTestID(),student.getUserID());
		try {
			ms.client.sendToServer(MsgSt);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
	}
	
	public void automaticCloser() 
	{
		
		Timer timer = new Timer();
		TimerTask timerTask = new TimerTask() {
		int flag =0;	
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				try {
					String now = DateUtils.now(DateUtils.hour+":"+DateUtils.minutes);
					lblClock.setText("Clock: "+ now);
					background.add(lblClock);
					//clock.setText("Time : "+now);
					//add(clock);
					//testDuration.setText("Test duration: "+Integer.toString(ms.stdnt.getExecuteTest().getTest().getTestDuration())+" minutes");
					MessageExtraTimeCheck MsgEtc = new MessageExtraTimeCheck(student.getUserID(), executeTest.getExecuteTestID());
					ms.client.sendToServer(MsgEtc);
					MessageExtraTimeCheckReply msgetr = (MessageExtraTimeCheckReply)ms.client.GetMessage();
					if (msgetr.getErrMsg() == ErrMsg.TIME_OVER)
					{
						JOptionPane.showMessageDialog(null,"Time is over!");
						uploadTest.setEnabled(false);
						 ms.stdnt.repaint();
						ms.setContentPane(ms.stdnt);
						this.cancel();
					}
					if (msgetr.getErrMsg() == ErrMsg.STOP_BY_TEACHER)
					{
						JOptionPane.showMessageDialog(null,"Test locked by teacher!");
						uploadTest.setEnabled(false);
						 ms.stdnt.repaint();
						ms.setContentPane(ms.stdnt);
						this.cancel();
					}
					if (msgetr.getErrMsg() == ErrMsg.ADD_EXTRA_TIME)
					{
						if (flag == 0)
						{
							JOptionPane.showMessageDialog(null, msgetr.getExtraTime()+" minutes is added to the test");
							lblTestDuration.setText("Test Duration: "+(executeTest.getTest().getTestDuration()+msgetr.getExtraTime())+" minutes");
							background.add(lblTestDuration);
							flag = 1;
						}
							
					}
					
					

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		};
		
		timer.schedule(timerTask, 0, 60*1000);
	
	

	}
}
